import { Button, Card, message } from 'antd';
import { Form } from '@ant-design/compatible';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import PateoTable from '../../../components/common/PateoTable';
import * as G from '../../../utils/common';
import AuthModal from './authModal';
import EditModal from './editModal';
import SyncFieldModal from './syncFieldModal';
import { filterAuth } from '@/support/common';
import OperateRecordModal from './operateRecordModal';
import MerchantDetailModal from './detailModal';
import { merchantsType } from '@/utils/enums';
import MaskText, { emailExp, formatFn, nameExp, phoneExp } from '@/components/MaskText';

let pageObj = {};

@Form.create()
class Merchant extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
    authButton: PropTypes.array,
  };

  state = {
    formValues: {},
    modalVisible: false,
    formData: '',
    authVisible: false,
    detailModalVisible: false,
    operateModalVisible: false,
    syncFieldModalVisible: false,
    isEdit: false,
  };

  componentDidMount() {
    this.init();
    this.handleFlushPage();
  }

  init = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/clearData',
      payload: {},
    });
  };

  //页面刷新方法
  handleFlushPage = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/pageablePost',
      payload: { url: '/mscreditbusiness/merchants/manage/list', delFlag: 0 },
    });
  };

  onRef = ref => {
    this.edit = ref;
  };

  onAuthRef = ref => {
    this.auth = ref;
  };

  onRoleRef = ref => {
    this.role = ref;
  };

  handleAuth = uuid => {
    const { dispatch } = this.props;
    dispatch({
      type: 'merchant/getDataWithRes',
      payload: { url: '/mscreditbusiness/merchants/autorisk', merchantsUuid: uuid },
      callback: response => {
        if (response.statusCode === '0') {
          this.setState({
            authVisible: true,
          });
          // const find = response.data.find((e) => e.type == 'all_vehicle');

          this.auth.formatData(response.data);
          this.auth.setStateData({
            merchantId: uuid,
            resultData: response.data,
            // tboxWakeupAuth: find && find.tboxWakeupAuth ? 1 : 0,
            // iviNoticeAuth: find && find.iviNoticeAuth ? 1 : 0,
          });
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };

  changeSyncFieldModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      // this.handleTableData();
      this.setState({
        syncFieldModalVisible: false,
      });
    } else {
      this.setState({
        syncFieldModalVisible: false,
      });
    }
  };

  //点击同步字段
  handleSyncField = uuid => {
    this.setState({
      syncFieldModalVisible: true,
      merchantId: uuid,
    });
  };

  //点击详情
  handleDetail = (uuid, isEdit) => {
    this.setState({
      detailModalVisible: true,
      isEdit,
    });
    this.getMerchantDetail(uuid).then(res => {
      let { merchantPhone, merchantUserMail, createBy } = res;
      this.detailForm.setData({
        ...res,
        merchantPhone: isEdit ? merchantPhone: formatFn({
          val: merchantPhone,
          regExp: phoneExp,
          length: 4,
        }),
        merchantUserMail: isEdit ? merchantUserMail: formatFn({
          val: merchantUserMail,
          regExp: emailExp,
          length: 4,
        }),
        createBy: isEdit ? createBy: formatFn({
          val: createBy,
          regExp: nameExp,
        }),
      });
    });
  };
  getMerchantDetail = uuid => {
    console.log(uuid);
    return new Promise(resolve => {
      this.props.dispatch({
        type: 'merchant/getDataWithRes',
        payload: {
          url: '/mscreditbusiness/merchants/manage',
          uuid,
        },
        callback: res => {
          if (res && res.statusCode == '0') {
            resolve(res.data);
            // } else {
            //   message.error(res.statusMessage);
          }
        },
      });
    });
  };

  //操作记录
  handleRecord = uuid => {
    this.setState(
      {
        merchantId: uuid,
      },
      () => {
        this.setState({
          operateModalVisible: true,
        });
      },
    );
  };
  //点击删除
  handleDelete = uuid => {
    this.props.dispatch({
      type: 'merchant/delDataWithRes',
      payload: {
        url: `/mscreditbusiness/merchants/manage?uuid=${uuid}`,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleFlushPage();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      common: {
        data: { rows, pagination },
      },
      loading,
      location: { pathname = '/' },
      permissions,
      dispatch,
    } = this.props;
    pageObj = pagination;

    const {
      formValues,
      modalVisible,
      formData,
      authVisible,
      operateModalVisible,
      syncFieldModalVisible,
      detailModalVisible,
      merchantId,
      isEdit,
    } = this.state;

    const isAdd = filterAuth('merchant-add', permissions, pathname);
    const columns = [
      {
        title: '商户名称',
        dataIndex: 'name',
      },
      {
        title: '商户类型',
        dataIndex: 'type',
        render: v => merchantsType[v],
      },
      {
        title: '合作状态',
        dataIndex: 'state',
        width: 90,
        render: text => {
          if (text === 0) {
            return '未生效';
          } else if (text === 1) {
            return '生效中';
          } else if (text === 2) {
            return '已过期';
          }
        },
      },
      {
        title: '商户账号',
        dataIndex: 'merchantName',
      },
      {
        title: '商户负责人手机号',
        dataIndex: 'merchantPhone',
        render(val) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '商户邮箱',
        dataIndex: 'merchantUserMail',
        render(val) {
          return <MaskText text={val} type="email" />;
        },
      },
      {
        title: '合作开始日',
        dataIndex: 'startDate',
        width: 95,
      },
      {
        title: '合作截止日',
        dataIndex: 'endDate',
        width: 95,
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: '',
        fixed: 'right',
        width: 235,
        render: (text, record) => {
          let btns = [
            {
              title: '自动风控规则车控授权',
              key: 'auth',
              auth: 'merchant-auth',
              onConfirm: () => {
                this.handleAuth(record.uuid);
              },
              hide: String(record.type) === '1',
            },
            {
              title: '字段同步',
              key: 'syncField',
              auth: 'merchant-sync',
              onConfirm: () => this.handleSyncField(record.uuid),
              hide: String(record.type) === '1',
            },
            {
              title: '查看',
              key: 'detail',
              auth: 'merchant-detail',
              onConfirm: () => this.handleDetail(record.uuid, false),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'merchant-edit',
              onConfirm: () => this.handleDetail(record.uuid, true),
            },
            {
              title: '操作记录',
              key: 'record',
              auth: 'merchant-record',
              onConfirm: () => this.handleRecord(record.uuid),
            },
          ];

          // if (isDel) {
          if (record.state !== 1) {
            btns.push({
              title: '删除',
              key: 'delete',
              auth: 'merchant-del',
              Popconfirm: true,
              message: '是否要删除商户?',
              onConfirm: () => this.handleDelete(record.uuid),
            });
          }
          // }
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];

    const searchItems = [
      {
        title: '商户名称',
        type: 'input',
        key: 'name',
      },
      {
        title: '合作状态',
        type: 'select',
        key: 'state',
        selectOptions: [
          { value: 0, label: '未生效' },
          { value: 1, label: '生效中' },
          { value: 2, label: '已过期' },
        ],
      },
    ];

    const tableProps = {
      rowKey: record => record.sid,
      columns,
      dataSource: rows,
      size: 'small',
      loading,
      pagination: G.paginationProps(pagination),
      scroll: { x: 'max-content' },
    };

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'common/pageablePost',
              url: '/mscreditbusiness/merchants/manage/list',
            }}
            saveFormValues={val => this.setState({ formValues: Object.assign(formValues, val) })}
            handleFormReset={() => this.setState({ formValues: {} })}
            extraArgs={{ delFlag: 0 }}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {isAdd && (
              <Button
                type="primary"
                size="small"
                htmlType="submit"
                onClick={() => {
                  this.setState({ modalVisible: true });
                }}
              >
                新增商户
              </Button>
            )}
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'common/pageablePost',
              url: '/mscreditbusiness/merchants/manage/list',
              extraArgs: { delFlag: 0 },
            }}
            currentName="curPage"
            formValues={formValues}
          />
        </Card>
        <EditModal
          onRef={this.onRef}
          modalVisible={modalVisible}
          dispatch={this.props.dispatch}
          closeModal={() => {
            this.setState({ modalVisible: false, formData: '' });
          }}
          formData={formData}
        />
        {authVisible && (
          <AuthModal
            onRef={this.onAuthRef}
            modalVisible={authVisible}
            dispatch={this.props.dispatch}
            closeModal={() => {
              this.setState({ authVisible: false });
            }}
          />
        )}
        {detailModalVisible && (
          <MerchantDetailModal
            onRef={val => (this.detailForm = val)}
            modalVisible={detailModalVisible}
            isEdit={isEdit}
            closeModal={() => {
              this.setState({
                detailModalVisible: false,
              });
            }}
          />
        )}
        {syncFieldModalVisible && (
          <SyncFieldModal
            merchantId={merchantId}
            changeSyncFieldModalVisible={this.changeSyncFieldModalVisible}
          />
        )}
        {operateModalVisible ? (
          <OperateRecordModal
            dispatch={this.props.dispatch}
            merchantId={merchantId}
            changeOperateModalVisible={() => {
              this.setState({
                operateModalVisible: false,
              });
            }}
          />
        ) : null}
      </div>
    );
  }
}

export default connect(state => {
  return {
    common: state.common,
    loading: state.loading.effects['common/pageGet'],
    permissions: state?.menu?.permissions,
    merchant: state.merchant,
  };
})(Merchant);
